<?php

namespace App\Jobs;

use App\Models\UserBalanceLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\WeekProfitReturn;
use App\Models\AdminUser;
use App\Handlers\WithdrawalHandler;


class WeekProfitReturnJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     * 本队列 默认延时 900 秒执行
     * @return void
     */
    public function __construct($ttl = 900)
    {
        $this->delay($ttl);
    }

    /**
     * Execute the job.
     * 佣金结算，把佣金划到用户帐户 和 流水记录表
     * @return void
     */
    public function handle()
    {
        // 周1至6
        list($t1, $t2) = [getStartOfWeek(), getEndOfWeek(6)];
        $WeekProfitReturn = WeekProfitReturn::with('admin_user')
            ->whereBetween('created_at', [$t1, $t2])
            ->where('ismail', 1)->get();

        $user_balance_log = UserBalanceLog::whereBetween('created_at', [$t1, $t2])
            ->where('type', 1)->where('amount_type', 2)->get();// 流水记录表


        foreach ($WeekProfitReturn as $k => $v) {
            $result = $user_balance_log->where('user_id', $v->user_id)->first();

            if (!$result) {// 本周流水记录表有记录，不进行返佣金
                $v->admin_user->profit_checkout = $v->profit_count + $v->zt_volume + $v->yj_volume + $v->zt_profit + $v->yj_profit + $v->tj_profit;
                if (WithdrawalHandler::UserBalanceLog($v->admin_user, '周结算佣金：'.$v->user_id, 2, 1)) {
                    $v->ismail = 2;
                    $v->save();
                }
            }
        }
    }
}
